package com.kk.score.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author KK
 * @CreateTime 2022/5/14
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin() //自定义编写的登录页面
                .loginPage("/login")//登录页面设置
                .and()
                //关闭csrf
                .csrf().disable()
                .headers().frameOptions().sameOrigin().and()
                .authorizeRequests()
                // 对登录接口 允许匿名访问
                .antMatchers(
                        "/user/login" //登录接口
                ).anonymous()

                //是否登录都不影响访问
                .antMatchers(
                        "/login",
                        "/user/login",
                        "/favicon.ico"
                ).permitAll()
                .antMatchers("/index.html").hasAnyRole("ROLE_ADMIN")
                // 除上面外的所有请求全部需要权限认证
                .anyRequest().authenticated()
                .and()
                //退出登陆相关的逻辑
                .logout()
                //自定义退出的url---默认的为/logout
                .logoutUrl("/user/logout")
                //自定义退出成功后跳转的url与logoutSuccessHandler互斥
                .logoutSuccessUrl("/login")
                //指定退出成功后删除的cookie
                .deleteCookies("JSESSIONID")
        ;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/static/**");
    }
}